from django.test import TestCase

import datetime
from django.utils import timezone
from django.urls import reverse
import time

from .models import Question


def create_question(question_text, days):
    publish_time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text,
                                   pub_date=publish_time)


class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        future_time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=future_time)
        self.assertIs(future_question.was_published_recently(), False)

    def test_past_question(self):
        create_question('past question', -30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(response.context['latest_question_list'],
                                 ['<Question: past question>'])

    def test_on_questions(self):
        respons = self.client.get(reverse('polls:index'))
        self.assertEqual(respons.status_code, 200)
        self.assertContains(respons,'暂无信息')
        self.assertQuerysetEqual(respons.context['latest_question_list'],[])

    def test_two_past_question(self):
        create_question('敌军还有30天到达战场', -30)
        create_question('敌军还有五天到达战场', -5)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: 敌军还有五天到达战场>', '<Question: 敌军还有30天到达战场>']
        )

    def test_future_question_and_past_question(self):
        create_question('30天之前发布的', -30)
        create_question('30天后发布的', 30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(response.context['latest_question_list'],
                                 ['<Question: 30天之前发布的>'])


class QuestionDetailViewTests(TestCase):

    def test_future_question(self):
        future_question = create_question(question_text='lxp', days=5)
        url = reverse('polls:detail', args=(future_question.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_past_question(self):
        past_question = create_question(question_text='我想吃炸鸡',days=-5)
        url = reverse('polls:detail', args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)


